package xuanze;

import java.util.Arrays;

public class SortCode {
    public static void main(String[] args) {
        b();
    }

    //选择排序法
    public static void a() {
        int[] arr = {1, 5, 4, 8, 6, 9};
        int p, r;
        for (int i = 0; i < arr.length - 1; i++) {
            p = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[p]) {
                    p = j;
                }
            }
            //与查找范围内的第一个数交换
            if (p != i) {
                r = arr[p];
                arr[p] = arr[i];
                arr[i] = r;
            }
        }
        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
    }

    private static void b() {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) (Math.random() * 10 + 1);
        }
        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
        System.out.println("开始进行选择排序法");
        long begin = System.currentTimeMillis();
        for (int j = 0; j < arr.length - 1; j++) {
            int min = arr[j];
            int minIndex = j;
            for (int i = j + 1; i < arr.length; i++) {
                if (min > arr[i]) {
                    min = arr[i];
                    minIndex = i;
                }
            }
            // 交换元素（最小值和第`一`个）
            int temp = arr[j];
            arr[j] = arr[minIndex];
            arr[minIndex] = temp;
        }
        System.out.println("Arrays.toString(arr) = " + Arrays.toString(arr));
        long end = System.currentTimeMillis();
        System.out.println("结束选择排序法");
        long time = end - begin;
        System.out.println("选择排序法花费时间是：" + time + "毫秒");

    }

}

